import { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from "@nestjs/common";
import { Response } from "express";
import { QueryFailedError } from "typeorm";
import Result from "../utils/result.util";

/** 处理数据库操作异常, 更新提示信息 */
@Catch(QueryFailedError)
export class DatabaseExceptionFilter implements ExceptionFilter {
    catch(exception: QueryFailedError, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();

        // PostgreSQL 错误码文档：
        // https://www.postgresql.org/docs/current/errcodes-appendix.html
        const driverError: any = exception.driverError;
        const code = driverError.code;
        let message = "数据库操作失败";

        switch (code) {
            case "23505": // unique_violation
                message = `数据已存在（唯一约束冲突）\n${driverError}`;
                break;
            case "23503": // foreign_key_violation
                message = "存在关联数据，无法删除";
                break;
            case "23502": // not_null_violation
                message = `字段 ${driverError.column} 不能为空`;
                break;
            default:
                message = `${code} ${driverError || message}`;
                break;
        }

        const status = HttpStatus.BAD_REQUEST;
        response.status(status).json(Result.exception(message, status));
    }
}
